import botpy
import yaml
from botpy import logger
import importlib
import pkgutil
from botpy.message import Message
from botpy.message import DirectMessage
from botpy.user import Member
import os


class MyClient(botpy.Client):
    def __init__(self, intents: botpy.Intents):
        super().__init__(intents=intents)
        self.plugins = self.load_plugins()
        with open('config/bot.yaml', 'r') as f:
            config = yaml.safe_load(f)
        self.appid = config.get('appid')
        self.token = config.get('token')

        while not self.appid or not self.token:
            print("请输入 appid 和 token（输入 Q 返回上级）：")
            self.appid = input("请输入 appid: ")
            if self.appid.lower() == 'q':
                self.appid = None  # 设置 appid 为空，用于返回上一级
                continue
            self.token = input("请输入 token: ")
            if self.token.lower() == 'q':
                self.appid = None  # 设置 appid 为空，用于返回上一级
                continue

            config['appid'] = self.appid
            config['token'] = self.token
            with open('config/bot.yaml', 'w') as f:
                yaml.dump(config, f)
        print("当前已装载插件个数：", len(self.plugins))

    async def toPlugin(self, message, eventNum):
        event = eventNum
        if event == 0 or event == 4:
            getname = await self.api.get_guild(guild_id=message.guild_id)
            logger.info(f'[{getname["name"]}][from {message.channel_id}]{message.author.username}:{message.content}')
        elif event == 1:
            logger.info(f'[频道私信][from {message.src_guild_id}]{message.author.username}:{message.content}')
        for plugin in self.plugins:
            if plugin.should_trigger(message, event):
                result = await plugin.execute(message, self.api, event)
                if result:
                    break

    def load_plugins(self):
        plugins = []
        package = "plugins"

        for name in os.listdir(package):
            if name.startswith('__pycache__') or name.endswith('.pyc'):
                continue

            path = os.path.join(package, name)
            if os.path.isdir(path):
                if name == "example":
                    for file_name in os.listdir(path):
                        if file_name.endswith(".py"):
                            module_name = f"{package}.{name}.{file_name[:-3]}"
                            module = importlib.import_module(module_name)
                            for attr_name in dir(module):
                                attr = getattr(module, attr_name)
                                if callable(attr) and hasattr(attr, "priority"):
                                    plugins.append(attr())
                else:
                    module_name = f"{package}.{name}.index"
                    module = importlib.import_module(module_name)
                    for attr_name in dir(module):
                        attr = getattr(module, attr_name)
                        if callable(attr) and hasattr(attr, "priority"):
                            plugins.append(attr())
            elif name.endswith(".py"):
                module_name = f"{package}.{name[:-3]}"
                module = importlib.import_module(module_name)
                for attr_name in dir(module):
                    attr = getattr(module, attr_name)
                    if callable(attr) and hasattr(attr, "priority"):
                        plugins.append(attr())

        return sorted(plugins, key=lambda p: p.priority(), reverse=True)

    # 频道消息转交插件处理
    async def on_message_create(self, message: Message):
        await self.toPlugin(message, 0)

    # 私聊消息转交插件处理
    async def on_direct_message_create(self, message: DirectMessage):
        await self.toPlugin(message, 1)

    # 新增成员移交插件处理
    async def on_guild_member_add(self, member: Member):
        await self.toPlugin(member, 2)

    # 移除成员移交插件处理
    async def on_guild_member_remove(self, member: Member):
        await self.toPlugin(member, 3)

    # 频道消息转交插件处理
    async def on_at_message_create(self, message: Message):
        await self.toPlugin(message, 4)


intents = botpy.Intents.all()
client = MyClient(intents=intents)
logger.info("欢迎使用阴天YT频道机器人!")
client.run(appid=client.appid, token=client.token)
